package controller;

import pojo.Manage;
import pojo.User;
import service.ManageService;
import service.UserService;
import view.SelfManageView;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class SelfManageListener implements ActionListener {
    private SelfManageView selfManageView;
    private String userId;
    public SelfManageListener(SelfManageView selfManageView, String userId){
        this.selfManageView = selfManageView;
        this.userId=userId;
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand().equals("续借")) {
            if (selfManageView.getJLabel3().getText().equals("")) {
                JOptionPane.showMessageDialog(selfManageView, "请选择一本图书", "提示", JOptionPane.WARNING_MESSAGE);
            }
            else{
            ManageService manageService = new ManageService();
            Manage manage = manageService.searchId(selfManageView.getJLabel3().getText());
            UserService service = new UserService();
            User user = service.search(userId);

            Timestamp t = Timestamp.valueOf(manage.getReturnTime());
            Calendar c = Calendar.getInstance();
            c.setTime(t);
//        c.add(Calendar.DATE, 1);  //  加一  天
            c.add(Calendar.MONTH, 1); //  加一个月
            //c.add(Calendar.YEAR,1);   //  加一  年
            Timestamp time1 = new Timestamp(c.getTimeInMillis());
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//定义格式，不显示毫秒
            String str = df.format(time1);
            manage.setReturnTime(str);
                int i = JOptionPane.showConfirmDialog(null, "确认续借1个月吗?", "确认", JOptionPane.YES_NO_OPTION);
                if (i == 0) {
                    manageService.update(manage);
                    selfManageView.refresh();
                }
        }
    }
        if(e.getActionCommand().equals("归还")) {
            ManageService manageService = new ManageService();
            if (selfManageView.getJLabel3().getText().equals("")) {
                JOptionPane.showMessageDialog(selfManageView, "请选择一本图书", "提示", JOptionPane.WARNING_MESSAGE);
            }
            else {
                int i = JOptionPane.showConfirmDialog(null, "确认归还吗?", "确认", JOptionPane.YES_NO_OPTION);
                if (i == 0) {
                    manageService.delete(selfManageView.getJLabel3().getText());
                    selfManageView.refresh();
                }
            }
        }
    }
}
